package com.hanshg.cherry.service.impl;

import com.hanshg.cherry.dto.LoginUser;
import com.hanshg.cherry.mapper.PermissionMapper;
import com.hanshg.cherry.model.SysPermission;
import com.hanshg.cherry.model.SysUser;
import com.hanshg.cherry.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 柠檬水
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.getUser(username);
        if (sysUser == null){
            throw new UsernameNotFoundException("用户不存在,请联系柠檬水小哥哥!");
        }else if (sysUser.getStatus() == SysUser.Status.LOCKED){
            throw new LockedException("用户被锁定，请联系柠檬水小哥哥!");
        }else if (sysUser.getStatus() == SysUser.Status.DISABLED){
            throw new DisabledException("用户已作废,请联系柠檬水小哥哥!");
        }

        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(sysUser,loginUser);

        List<SysPermission> permissions = permissionMapper.listByUserId(sysUser.getId());
        loginUser.setPermissions(permissions);

        return loginUser;
    }
}
